package com.lin.linchatgpt.config;

import cn.hutool.core.util.StrUtil;
import com.lin.linchatgpt.entity.Message;
import com.lin.linchatgpt.entity.Subject;
import com.mybatisflex.core.keygen.IKeyGenerator;
import com.mybatisflex.core.keygen.KeyGeneratorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


import java.util.UUID;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/6/16 19:23
 * @Description
 */
@Configuration
public class MyUUIDGeneratorStrategy implements IKeyGenerator {
    @Override
    public Object generate(Object o, String s) {
        if ((o instanceof Message)){
            Message message = (Message) o;
            // 如果id为空，就生成一个id，否则就使用原来的id
            return getUUID(message.getId());
        }
        if ((o instanceof Subject)){
            Subject subject = (Subject) o;
            // 如果id为空，就生成一个id，否则就使用原来的id
            return getUUID(subject.getId());
        }
        return null;
    }

    String getUUID(String id){
        if(StrUtil.isBlank(id)){
            return UUID.randomUUID().toString().replace("-","");
        }
        return id;
    }


    @Autowired
    public void setKeyGenerate(){
        KeyGeneratorFactory.register("myUUID",new MyUUIDGeneratorStrategy());
    }

}
